package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.zhijian.medical.dao.local.SangerHschyq2Mapper;
import com.zhijian.medical.entity.dto.SangerSjpzqTxDto;
import com.zhijian.medical.entity.po.ExperimentProcessSampleLog;
import com.zhijian.medical.entity.po.Sanger;
import com.zhijian.medical.entity.po.SangerHschyq2;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleSearchVo;
import com.zhijian.medical.entity.vo.request.SangerHschyq2SaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.SangerHschyq2SearchVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleVo;
import com.zhijian.medical.entity.vo.response.SangerHschyq2Vo;
import com.zhijian.medical.enums.AllExperimentationStepStatusEnum;
import com.zhijian.medical.enums.ExperimentTypeEnum;
import com.zhijian.medical.enums.SangerStatusEnum;
import com.zhijian.medical.enums.StatusEnum;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.ExperimentProcessSampleLogService;
import com.zhijian.medical.service.ExperimentProcessSampleService;
import com.zhijian.medical.service.SangerHschyq2Service;
import com.zhijian.medical.service.SangerService;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.JsonUtil;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 一代测序-核酸纯化一区 （测序PCR试剂配制与加样） 业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-08-12 14:44:14
 */
@Slf4j
@Service
public class SangerHschyq2ServiceImpl implements SangerHschyq2Service {

    @Autowired
    private SangerHschyq2Mapper mapper;

    @Autowired
    private SangerService sangerService;

    @Autowired
    private ExperimentProcessSampleService experimentProcessSampleService;

    @Autowired
    private ExperimentProcessSampleLogService experimentProcessSampleLogService;

    @Override
    public SangerHschyq2 selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public SangerHschyq2 selectBySangerId(Long sangerId) {
        return mapper.selectBySangerId(sangerId);
    }

    @Override
    public SangerHschyq2Vo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public SangerHschyq2Vo selectVoBySangerId(Long sangerId) {
        SangerHschyq2Vo sangerHschyq2Vo = mapper.selectVoBySangerId(sangerId);
        if (Objects.isNull(sangerHschyq2Vo)) {
            return null;
        }
        Sanger sanger = sangerService.selectById(sangerId);
        if (Objects.isNull(sanger)) {
            return null;
        }
        sangerHschyq2Vo.setResult(sanger.getStatus() > SangerStatusEnum.HSCHYQ2.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getCode().byteValue() : AllExperimentationStepStatusEnum.UN_END.getCode().byteValue());
        sangerHschyq2Vo.setResultStr(sanger.getStatus() > SangerStatusEnum.HSCHYQ2.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getDesc() : AllExperimentationStepStatusEnum.UN_END.getDesc());
        String sjphjfytxdpzData = sangerHschyq2Vo.getSjphjfytxdpzData();
        if (StringUtils.isNotBlank(sjphjfytxdpzData)) {
            sangerHschyq2Vo.setSjphjfytxdpzDataList(JsonUtil.toArray(sjphjfytxdpzData, SangerSjpzqTxDto.class));
        }
        return sangerHschyq2Vo;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long insert(SangerHschyq2 sangerHschyq2) {
        Date now = new Date();
        sangerHschyq2.setCreateTime(now);
        sangerHschyq2.setUpdateTime(now);
        sangerHschyq2.setSytmqj(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq2.setSjzyxqn(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq2.setAzfzzsop010(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq2.setLx(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq2.setGcywyc(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq2.setSjphjfytxdpz(StatusEnum.NORMAL.getCode().byteValue());
        sangerHschyq2.setLxj(StatusEnum.NORMAL.getCode().byteValue());
        sangerHschyq2.setAqg(StatusEnum.NORMAL.getCode().byteValue());
        sangerHschyq2.setQjjzwzssygztm(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq2.setQjyyq(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq2.setQjlxj(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq2.setClsyfqw(StatusEnum.UN_NORMAL.getCode().byteValue());
        return mapper.insert(sangerHschyq2) > 0 ? sangerHschyq2.getId() : 0L;
    }

    @Override
    public boolean update(SangerHschyq2 sangerHschyq2) {
        Date now = new Date();
        sangerHschyq2.setUpdateTime(now);
        return mapper.updateByPrimaryKey(sangerHschyq2) != 0;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean saveOrUpdate(SangerHschyq2SaveOrUpdateVo sangerHschyq2SaveOrUpdateVo) {
        Long sangerId = sangerHschyq2SaveOrUpdateVo.getSangerId();
        Sanger sanger = sangerService.selectById(sangerId);
        AssertUtil.notNull(sanger, "此实验不存在或者已被删除");
        if (sanger.getStatus() < SangerStatusEnum.HSKZEQ1.getCode().byteValue()) {
            //将实验的状态修改
            sangerService.updateByPrimaryKeySelective(Sanger.builder()
                    .id(sangerId)
                    .status(SangerStatusEnum.HSKZEQ1.getCode().byteValue())
                    .build());
        }
        SangerHschyq2 oldSangerHschyq2 = this.selectBySangerId(sangerId);
        List<SangerSjpzqTxDto> sjphjfytxdpzDataList = sangerHschyq2SaveOrUpdateVo.getSjphjfytxdpzDataList();
        if (CollectionUtil.isNotEmpty(sjphjfytxdpzDataList)) {
            sangerHschyq2SaveOrUpdateVo.setSjphjfytxdpzData(JsonUtil.toString(sjphjfytxdpzDataList));
        }
        SangerHschyq2 sangerHschyq2 = new SangerHschyq2();
        BeanUtils.copyProperties(sangerHschyq2SaveOrUpdateVo, sangerHschyq2);
        if (Objects.isNull(oldSangerHschyq2)) {
            this.insert(sangerHschyq2);
        } else {
            sangerHschyq2.setId(oldSangerHschyq2.getId());
            this.update(sangerHschyq2);
        }
        List<ExperimentProcessSampleVo> experimentProcessSampleVos = experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .mainType(ExperimentTypeEnum.SANGER.getCode().byteValue())
                .experimentProcessId(sangerId)
                .build());
        //保存样本日志
        experimentProcessSampleLogService.saveBatch(experimentProcessSampleVos.stream().map(e -> ExperimentProcessSampleLog.builder()
                .sampleId(e.getId())
                .fishId(sangerId)
                .mainType(ExperimentTypeEnum.SANGER.getCode().byteValue())
                .op(String.format("%s%s-%s", sanger.getName(), sanger.getProcessNumber(), SangerStatusEnum.HSCHYQ2.getDesc()))
                .opUser(CurrentUserHolder.getUser().getName())
                .build()).collect(Collectors.toList()));
        return true;
    }

    @Override
    public Integer count(SangerHschyq2SearchVo sangerHschyq2SearchVo) {
        return mapper.count(sangerHschyq2SearchVo);
    }

    @Override
    public List<SangerHschyq2Vo> selectList(SangerHschyq2SearchVo sangerHschyq2SearchVo) {
        return mapper.selectList(sangerHschyq2SearchVo);
    }

    @Override
    public Page<SangerHschyq2Vo> selectPage(SangerHschyq2SearchVo sangerHschyq2SearchVo) {
        //先直接查总数
        int count = count(sangerHschyq2SearchVo);
        //分页
        Page<SangerHschyq2Vo> page = new Page<>(true, count, sangerHschyq2SearchVo.getPageNum(), sangerHschyq2SearchVo.getPageSize());
        sangerHschyq2SearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<SangerHschyq2Vo> responseVos = this.selectList(sangerHschyq2SearchVo);
        page.setData(responseVos);
        return page;
    }

}